﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace SingleInstanceApplication.Test
{
	public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();

			_processes = new List<Process>();

			Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);

			dataGridView1.Rows.Add(new object[] { "SingleInstanceApplication.WpfApp.exe", "aa bb cc" });
			dataGridView1.Rows.Add(new object[] { "SingleInstanceApplication.WinFormsApp.exe", "aa bb cc" });
			dataGridView1.Rows.Add(new object[] { "SingleInstanceApplication.ConsoleApp.exe", "aa bb cc" });

			dataGridView1.CellContentClick += dataGridView1_CellContentClick;
		}

		private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e == null || e.ColumnIndex != 2 || dataGridView1.Rows[e.RowIndex].IsNewRow) return;

			var filePath = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
			var args = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();

			var process = new Process();
			process.Exited += process_Exited;

			try
			{
				Process.Start(filePath, args);
				_processes.Add(process);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, Text);
			}
		}

		private void process_Exited(object sender, EventArgs e)
		{
			var process = sender as Process;
			if (process == null || !_processes.Contains(process)) return;
			_processes.Remove(process);
		}

		protected override void OnClosed(EventArgs e)
		{
			base.OnClosed(e);
			if (_processes.Count < 1) return;

			var ary = new Process[_processes.Count];
			_processes.CopyTo(ary, 0);
			_processes.Clear();

			foreach (var process in ary)
			{
				try
				{
					process.CloseMainWindow();
				}
				catch //(Exception ex)
				{
					//MessageBox.Show(ex.Message, Text);
				}
				finally
				{
					process.Dispose();
				}
			}
		}

		private readonly IList<Process> _processes;
	}
}
